import { ActionTree } from 'vuex';
import { RootState } from '@/store/root-state';
import { SET_PARAMS } from './mutations';
import { getParamList, ParamType } from '@/api/user/login';
import ls from '@/utils/local-storage';
import { TreeState } from './typing';
export const GET_TREE_PARAM = 'GET_TREE_PARAM';
export const CLEAR_TREE_PARAM = 'CLEAR_TREE_PARAM';

export const actions: ActionTree<TreeState, RootState> = {
  [GET_TREE_PARAM]({ commit }) {
    return new Promise((resolve, reject) => {
      const classifyTree = ls.get('classifyTree') || [];
      const callTree = ls.get('callTree') || [];
      const dealTree = ls.get('dealTree') || [];
      const xqdwTree = ls.get('xqdwTree') || [];
      if (classifyTree && classifyTree.length) {
        commit(SET_PARAMS, { classifyTree, callTree, dealTree, xqdwTree });
        resolve(true);
        return false;
      }
      getParamList()
        .then(res => {
          const { classifyTree = [], callTree = [], dealTree = [], xqdwTree = [] } = res.data;
          ls.set('classifyTree', classifyTree);
          ls.set('callTree', callTree);
          ls.set('dealTree', dealTree);
          ls.set('xqdwTree', xqdwTree);
          commit(SET_PARAMS, res.data);
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  [CLEAR_TREE_PARAM]({ commit }) {
    return new Promise((resolve, reject) => {
      commit(SET_PARAMS, { classifyTree: [], callTree: [], dealTree: [], xqdwTree: [] });
      ls.set('classifyTree', []);
      ls.set('callTree', []);
      ls.set('dealTree', []);
      ls.set('xqdwTree', []);
      resolve(true);
    });
  },
};
